import 'package:excel_utils/extend/string_extend.dart';
import 'package:excel_utils/pages/view/calendar_view.dart';
import 'package:excel_utils/pages/week/bean/MonthlyPackageTransferBean.dart';
import 'package:excel_utils/pages/week/week_entry/child/monthly_package_transfer/bloc/monthly_package_transfer_cubit.dart';
import 'package:excel_utils/pages/week/week_report/week_isolate/week_isloate.dart';
import 'package:excel_utils/repository/k8/k8_repository.dart';
import 'package:excel_utils/repository/week/monthly_package_transfer_repository.dart';
import 'package:excel_utils/widgets/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class MonthlyPackageTransferPage extends StatefulWidget {
  const MonthlyPackageTransferPage({super.key});

  @override
  State<MonthlyPackageTransferPage> createState() => _MonthlyPackageTransferPageState();
}

class _MonthlyPackageTransferPageState extends State<MonthlyPackageTransferPage> {
  MonthlyPackageTransferCubit? monthlyPackageTransferCubit;

  late DateTime? startDate;
  late DateTime? endDate;

  String? monthFeeStartDate = "";
  String? monthFeeEndDate = "";

  List<MonthlyPackageTransferBean> monthlyPackageTransferData = [];
  bool searchLoading = false;
  Set<String> deleteIdData = {};
  bool saveLoading = false;

  int year = 2025;
  int month = 09;
  int day = 04;

  dynamic originalMonthlyFeeAll = 0;
  dynamic quantityKeDaAll = 0;
  dynamic sellingSilverCodeAll = 0;
  dynamic numberPackageTicketsAll = 0;
  dynamic sellingSilverCode_C_monthlyPackageTransferData = 0;

  Set<String> searchCustomerNo = {};

  @override
  void initState() {
    DateTime today = DateTime.now();
    // 判断今天是周几
    int currentWeekday = DateTime.now().weekday;
    // 如果是周三，则修改开始日期为周四
    int daysToSubtract = (currentWeekday - 3 + 7) % 7 + 7;
    DateTime lastWednesday = today.subtract(Duration(days: daysToSubtract));
    startDate = lastWednesday;
    startDate = DateTime(startDate!.year, startDate!.month, startDate!.day + 1, 00, 00, 00);
    //结束日期为今天
    endDate = today;
    endDate = DateTime(endDate!.year, endDate!.month, endDate!.day, 23, 59, 59);
    year = endDate!.year;
    month = endDate!.month;
    day = endDate!.day;

    print("startDate: $startDate");
    print("endDate: $endDate");

    monthFeeStartDate = "${startDate?.year}-${startDate?.month.toString().padLeft(2, '0')}-${startDate?.day.toString().padLeft(2, '0')}";
    monthFeeEndDate = "${endDate?.year}-${endDate?.month.toString().padLeft(2, '0')}-${endDate?.day.toString().padLeft(2, '0')}";

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<MonthlyPackageTransferCubit>(
      create: (_) => MonthlyPackageTransferCubit(context.read<MonthlyPackageTransferRepository>(), context.read<K8Repository>()),
      child: BlocConsumer<MonthlyPackageTransferCubit, MonthlyPackageTransferState>(
        builder: (BuildContext context, MonthlyPackageTransferState state) {
          monthlyPackageTransferCubit = monthlyPackageTransferCubit ?? context.read<MonthlyPackageTransferCubit>();

          if (state is MonthlyPackageTransferInitial) {
          } else if (state is MonthlyPackageTransferDataLoading) {
            searchLoading = true;
          } else if (state is MonthlyPackageTransferDataSuccessState) {
            searchLoading = false;
            monthlyPackageTransferData = state.monthlyPackageTransferData;
            try {
              originalMonthlyFeeAll = monthlyPackageTransferData.fold(0.0, (value, element) => value + element.originalMonthlyFee!);
              quantityKeDaAll = monthlyPackageTransferData.fold(0, (value, element) => value + element.quantityKeDa!);
              sellingSilverCodeAll = monthlyPackageTransferData.fold(0.0, (value, element) => value + element.sellingSilverCode!);
              numberPackageTicketsAll = monthlyPackageTransferData.fold(0, (value, element) => value + element.numberPackageTickets!);
              sellingSilverCode_C_monthlyPackageTransferData = monthlyPackageTransferData.fold(0.0, (value, element) => value + element.sellingSilverCode!) /
                  monthlyPackageTransferData.fold(0, (value, element) => value + element.numberPackageTickets!);
            } catch (ex) {}
          } else if (state is MonthlyPackageTransferDataFailureState) {
            searchLoading = false;
          } else if (state is MonthlyPackageTransferDeleteLoading) {
            deleteIdData.add(state.monthlyPackageTransferId);
          } else if (state is MonthlyPackageTransferDeleteSuccessState) {
            deleteIdData.remove(state.monthlyPackageTransferId);
          } else if (state is MonthlyPackageTransferDeleteFailureState) {
            deleteIdData.remove(state.monthlyPackageTransferId);
          } else if (state is MonthlyPackageTransferSaveLoading) {
            saveLoading = true;
          } else if (state is MonthlyPackageTransferSaveSuccessState) {
            saveLoading = false;
            monthlyPackageTransferData = state.monthlyPackageTransferData;
          } else if (state is MonthlyPackageTransferSearchCustomerLoading) {
            searchCustomerNo.add(state.customerNo);
          } else if (state is MonthlyPackageTransferSearchCustomerSuccessState) {
            searchCustomerNo.remove(state.customerNo);
            // 查询数据，获取到对应的index
            for (var element in monthlyPackageTransferData) {
              if (element.newCustomerNo == state.customerNo) {
                int index = monthlyPackageTransferData.indexOf(element);

                monthlyPackageTransferData[index].groupName = state.customerBean.data![0].bcName;

                String groupNameStr = getGroupName(state.customerBean.data![0].cmCode.toString(), state.customerBean.data![0].bcName.toString());
                monthlyPackageTransferData[index].groupName = groupNameStr;

                monthlyPackageTransferData[index].newCustomerNo = state.customerBean.data![0].cmCode;
                monthlyPackageTransferData[index].region = state.customerBean.data![0].cmAddress;

                monthlyPackageTransferData[index].sellingSilverCode = double.parse(state.customerBean.data![0].cmMonthcost.toString());
                monthlyPackageTransferData[index].numberPackageTickets = state.customerBean.data![0].cmOrdernum;
                monthlyPackageTransferData[index].average =
                    (monthlyPackageTransferData[index].sellingSilverCode)! / (monthlyPackageTransferData[index].numberPackageTickets!);
              }
            }
          }

          return buildUI();
        },
        listener: (BuildContext context, MonthlyPackageTransferState state) {},
      ),
    );
  }

  Widget buildUI() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "月費套票互轉客戶紀錄",
            style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.blue),
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CalendarView(
                onInitDateChanged: (startDateTime, startStr, endDateTime, endStr) {
                  // monthFeeStartDate = "${startStr}";
                  // monthFeeEndDate = "${endStr}";
                },
                onDateStartChanged: (startDateTime, startStr) {
                  print("disMonthFeeStartDate: $startDateTime, $startStr");
                  monthFeeStartDate = "${startStr}";
                },
                onDateEndChanged: (endDateTime, endStr) {
                  print("disMonthFeeEndDate: $endDateTime, $endStr");
                  monthFeeEndDate = "${endStr}";
                },
              ),
              searchLoading? Center(child: CircularProgressIndicator()) :
              ElevatedButton(
                child: Text("查询"),
                onPressed: () {
                  monthlyPackageTransferCubit?.getMonthlyPackageTransfer(maps: {
                    "startDate": monthFeeStartDate,
                    "endDate": monthFeeEndDate,
                  });
                },
              ),
            ],
          ),
          Table(
            children: [
              tabRows(
                  ["No", "收到日期", "群組", "直客/加盟商", "新客戶號碼", "客戶名稱", "地區", "原月費", "柯打數量", "銷售銀碼", "套票數量", "平均/張", "有效期", "舊客戶號碼", "舊客戶停用日期", "備註", "日期范围", "操作"]),
              ...monthlyPackageTransferData.asMap().entries.map((element) {
                MonthlyPackageTransferBean e = element.value;
                return tabRowWidgets([
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: (element.key + 1).toString()),
                    readOnly: true,
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.receivedDate ?? ""),
                    onChanged: (value) => e.receivedDate = value.replaceAll("\r", ""),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.groupName ?? ""),
                    onChanged: (value) => e.groupName = value.replaceAll("\r", ""),
                  ),
                  Container(
                    child: DropdownMenu(
                      dropdownMenuEntries: [
                        DropdownMenuEntry(value: 1, label: "CXC直客"),
                        DropdownMenuEntry(value: 2, label: "加盟商"),
                      ],
                      label: Text(e.directFranchisee == 1 ? "直客" : "加盟商"),
                      onSelected: (value) {
                        e.directFranchisee = value;
                        monthlyPackageTransferCubit?.refresh();
                      },
                    ),
                  ),
                  Container(
                    child: Stack(
                      children: [
                        TextField(
                          decoration: const InputDecoration(border: OutlineInputBorder()),
                          controller: TextEditingController(text: e.newCustomerNo ?? ""),
                          onChanged: (value) => e.newCustomerNo = value.replaceAll("\r", ""),
                        ),
                        Positioned(
                          right: 0,
                          top: 0,
                          child: IconButton(
                            icon: Icon(Icons.search),
                            onPressed: () {
                              monthlyPackageTransferCubit?.searchCustomer(customerNo: e.newCustomerNo.toString().replaceAll("\r", ""));
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.customerName ?? ""),
                    onChanged: (value) => e.customerName = value.replaceAll("\r", ""),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.region ?? ""),
                    onChanged: (value) => e.region = value.replaceAll("\r", ""),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: "${e.originalMonthlyFee}"),
                    onChanged: (value) {
                      try {
                        e.originalMonthlyFee = double.parse(value.replaceAll("\r", ""));
                      } catch (ex) {
                        e.originalMonthlyFee = 0.00;
                      }
                    },
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: "${e.quantityKeDa ?? 0}"),
                    onChanged: (value) {
                      try {
                        String valueStr = value.trim().toString();

                        e.quantityKeDa = int.parse(valueStr);
                      } catch (ex) {
                        e.quantityKeDa = 0;
                      }
                    },
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: "${e.sellingSilverCode}"),
                    onChanged: (value) {
                      try {
                        e.sellingSilverCode = double.parse(value.replaceAll("\r", ""));
                      } catch (ex) {
                        e.sellingSilverCode = 0;
                      }
                    },
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.numberPackageTickets.toString()),
                    onChanged: (value) {
                      try {
                        e.numberPackageTickets = int.parse(value.replaceAll("\r", ""));
                      } catch (ex) {
                        e.numberPackageTickets = 0;
                      }
                    },
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.average.toString()),
                    onChanged: (value) {
                      try {
                        e.average = double.parse(value.replaceAll("\r", ""));
                      } catch (ex) {
                        e.average = 0.00;
                      }
                    },
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.validityPeriod ?? ""),
                    onChanged: (value) => e.validityPeriod = value.replaceAll("\r", ""),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.oldCustomerNumber ?? ""),
                    onChanged: (value) => e.oldCustomerNumber = value.replaceAll("\r", ""),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.oldCustomerDisDate ?? ""),
                    onChanged: (value) => e.oldCustomerDisDate = value.replaceAll("\r", ""),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.remark ?? ""),
                    onChanged: (value) => e.remark = value.replaceAll("\r", ""),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.dateRange ?? ""),
                    onChanged: (value) => e.dateRange = value.replaceAll("\r", ""),
                  ),
                  TextButton(
                      onPressed: () {
                        if (e.id == null) {
                          monthlyPackageTransferData.removeAt(element.key);
                          monthlyPackageTransferCubit?.refresh();
                        } else {
                          monthlyPackageTransferCubit?.delMonthlyPackageTransfer(monthlyPackageTransferId: e.id.toString());
                        }
                      },
                      child: Text("Del")),
                ]);
              }),
              tabRows([
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                "${originalMonthlyFeeAll}",
                "${quantityKeDaAll}",
                "${sellingSilverCodeAll}",
                "${numberPackageTicketsAll}",
                "${sellingSilverCode_C_monthlyPackageTransferData}",
                "",
                "",
                "",
                "",
                "",
                ""
              ]),
              // 汇总
              tabRows(
                  ["日期", "原月費 總收入", "轉套票後銷售收入", "加-原月費 總收入", "加-轉套票後銷售收入", "加-客戶數目", "C-原月費總收入", "C-轉套票後銷售收入", "C-客戶數目", "", "", "", "", "", "", "", "", ""]),
              tabRows([
                // "${monthFeeStartDate?.substring(5, 10)}-${monthFeeEndDate?.substring(5, 10)}",
                "",
                "${originalMonthlyFeeAll}",
                "${sellingSilverCodeAll}",
                "${monthlyPackageTransferData.fold(0.0, (value, element) {
                  if (element.directFranchisee != 1) {
                    // 加盟商
                    return value + element.originalMonthlyFee!;
                  }
                  return value;
                })}",
                "${monthlyPackageTransferData.where((element) => element.directFranchisee != 1).length}",
                "${monthlyPackageTransferData.fold(0.0, (value, element) {
                  if (element.directFranchisee != 1) {
                    // 加盟商
                    return value + element.sellingSilverCode!;
                  }
                  return value;
                })}",
                "${monthlyPackageTransferData.fold(0.0, (value, element) {
                  if (element.directFranchisee == 1) {
                    // c
                    return value + element.originalMonthlyFee!;
                  }
                  return value;
                })}",
                "${monthlyPackageTransferData.fold(0.0, (value, element) {
                  if (element.directFranchisee == 1) {
                    // c
                    return value + element.sellingSilverCode!;
                  }
                  return value;
                })}",
                "${monthlyPackageTransferData.where((element) => element.directFranchisee == 1).length}",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                ""
              ]),
            ],
          ),
          Row(
            children: [
              SizedBox(width: 10),
              ElevatedButton(
                  onPressed: () {
                    StringBuffer sb = StringBuffer();
                    for (int index = 0; index < monthlyPackageTransferData.length; index++) {
                      MonthlyPackageTransferBean monthlyPackageTransfer = monthlyPackageTransferData[index];
                      String tempStr = "";
                      tempStr += "${index + 1}\t";
                      tempStr += "${monthlyPackageTransfer.receivedDate ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.groupName ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.newCustomerNo ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.customerName ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.region ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.originalMonthlyFee ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.quantityKeDa ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.sellingSilverCode ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.numberPackageTickets ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.average ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.validityPeriod ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.oldCustomerNumber ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.oldCustomerDisDate ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.remark ?? ""}\t";
                      sb.writeln(tempStr);
                    }
                    String summary = "";
                    summary += "\t\t\t\t\t\t";
                    summary +=
                        "${originalMonthlyFeeAll}\t${quantityKeDaAll}\t${sellingSilverCodeAll}\t${numberPackageTicketsAll}\t${sellingSilverCode_C_monthlyPackageTransferData}\t";
                    summary += "\t\t\t\t\t\t";
                    sb.writeln(summary);
                    sb.toString().copyValue();
                  },
                  child: Text("COPY")),
              ElevatedButton(
                  onPressed: () {
                    StringBuffer sb = StringBuffer();

                    sb.write("${monthFeeStartDate?.substring(5, 10)}-${monthFeeEndDate?.substring(5, 10)}\t");
                    sb.write("${originalMonthlyFeeAll}\t");
                    sb.write("${sellingSilverCodeAll}\t");
                    sb.write("${monthlyPackageTransferData.fold(0.0, (value, element) {
                      if (element.directFranchisee != 1) {
                        // 加盟商
                        return value + element.originalMonthlyFee!;
                      }
                      return value;
                    })}\t");
                    sb.write("${monthlyPackageTransferData.where((element) => element.directFranchisee != 1).length}\t");
                    sb.write("${monthlyPackageTransferData.fold(0.0, (value, element) {
                      if (element.directFranchisee != 1) {
                        // 加盟商
                        return value + element.sellingSilverCode!;
                      }
                      return value;
                    })}\t");
                    sb.write("${monthlyPackageTransferData.fold(0.0, (value, element) {
                      if (element.directFranchisee == 1) {
                        // c
                        return value + element.originalMonthlyFee!;
                      }
                      return value;
                    })}\t");
                    sb.write("${monthlyPackageTransferData.fold(0.0, (value, element) {
                      if (element.directFranchisee == 1) {
                        // c
                        return value + element.sellingSilverCode!;
                      }
                      return value;
                    })}\t");
                    sb.write("${monthlyPackageTransferData.where((element) => element.directFranchisee == 1).length}\t");
                    sb.toString().copyValue();
                  },
                  child: Text("汇总")),
              SizedBox(width: 10),
              ElevatedButton(
                  onPressed: () {
                    DateTime now = DateTime.now();
                    now.month.toString().padLeft(2, '0');
                    String createDate = "${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}";
                    monthlyPackageTransferData.add(MonthlyPackageTransferBean(
                        receivedDate: "",
                        groupName: "",
                        newCustomerNo: "",
                        customerName: "",
                        region: "",
                        originalMonthlyFee: 0.00,
                        quantityKeDa: 0,
                        sellingSilverCode: 0,
                        numberPackageTickets: 0,
                        average: 0.00,
                        validityPeriod: "",
                        oldCustomerNumber: "",
                        oldCustomerDisDate: "",
                        remark: "",
                        dateRange: "",
                        createDate: "${createDate}"));
                    setState(() {});
                  },
                  child: Text("添加")),
              SizedBox(width: 10),
              saveLoading
                  ? CircularProgressIndicator()
                  : ElevatedButton(
                      onPressed: () {
                        bool isNotEmpty = false;
                        for (var monthlyPackageTransfer in monthlyPackageTransferData) {
                          if (monthlyPackageTransfer.receivedDate == "") {
                            isNotEmpty = true;
                            break;
                          }
                          if (monthlyPackageTransfer.groupName == "") monthlyPackageTransfer.groupName = " ";
                          if (monthlyPackageTransfer.customerName == "") monthlyPackageTransfer.customerName = " ";
                          if (monthlyPackageTransfer.region == "") monthlyPackageTransfer.region = " ";
                          monthlyPackageTransfer.originalMonthlyFee ??= 0.00;
                          monthlyPackageTransfer.quantityKeDa ??= 0;
                          monthlyPackageTransfer.sellingSilverCode ??= 0;
                          monthlyPackageTransfer.numberPackageTickets ??= 0;
                          monthlyPackageTransfer.average ??= 0.00;
                          if (monthlyPackageTransfer.validityPeriod == "") monthlyPackageTransfer.validityPeriod = " ";
                          if (monthlyPackageTransfer.oldCustomerNumber == "") monthlyPackageTransfer.oldCustomerNumber = " ";
                          if (monthlyPackageTransfer.oldCustomerDisDate == "") monthlyPackageTransfer.oldCustomerDisDate = " ";
                          if (monthlyPackageTransfer.remark == "") monthlyPackageTransfer.remark = " ";
                          if (monthlyPackageTransfer.dateRange == "") {
                            isNotEmpty = true;
                            break;
                          }
                        }
                        if (isNotEmpty) {
                          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("请填写完整数据")));
                          return;
                        }
                        monthlyPackageTransferCubit?.saveMonthlyPackageTransfer(monthlyPackageTransferData: monthlyPackageTransferData);
                      },
                      child: Text("保存")),
            ],
          ),
          SizedBox(height: 10),
        ],
      ),
    );
  }
}
